/*
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<fcntl.h>
*/
#include"server.h"
#define DATABASE "database"

int datbas_open(sqlite3 **db)
{
	char        *errmsg;
	/*
	   if(access(DATABASE,F_OK)!=-1)
	   {
	   printf("DATABASE exist.\n");

	   if(sqlite3_open(DATABASE,db)!=SQLITE_OK)
	   {

	   printf("sqlite3_open error:%s\n",sqlite3_errmsg(*db));
	   return -1;
	   }

	   }
	   */


	if(sqlite3_open(DATABASE,db)!=SQLITE_OK)//创建或打开数据库
	{

		printf("sqlite3_open error:%s\n",sqlite3_errmsg(*db));
	}

	printf("sqlite3_open success.\n");

	//判断数据库中的表是否存在，如果不存在则创建表
	if(sqlite3_exec(*db,"create table tempreature (ID char,temp char,time char);",NULL,NULL,&errmsg)!=SQLITE_OK)
	{
		printf("exectute create information:%s\n",errmsg);
	}


	return 0;
}


int datbas_insert(sqlite3 *db,char *ID,char *temp,char *time)
{
	char        *errmsg;

	char        sql[128];

	if(!db)
	{
		printf("Invalid input argument db!\n");
		return -1;
	}

	memset(sql,0,sizeof(sql)); 
	if(snprintf(sql, sizeof(sql), "insert into tempreature values('%s','%s','%s');",ID,temp,time)<0)
	{
		printf("sprintf error:%s\n",strerror(errno));
		return -1;
	}

	printf("sql: [%s]\n",sql);

	if((sqlite3_exec(db,sql,NULL,NULL,&errmsg)) != SQLITE_OK)
	{ 
		printf("insert failed:%s\n",errmsg);
		return -2;
	}
	printf("insert successfully\n");     

	return 0;
}


int datbas_close(sqlite3 *db)
{
	char     *errmsg;

	if(sqlite3_close(db)!=SQLITE_OK)
	{
		printf("close error:%s\n",sqlite3_errmsg(db));
		return 0;
	}

	return 0;

}
